package com.example.mananger.handler;

import com.alibaba.fastjson.JSONObject;
import com.example.base.app.AppHandler;
import com.example.base.app.AppHandlerServer;
import com.example.base.app.AppInterceptor;
import com.example.base.app.AppLoginHandler;
import com.example.base.security.domain.SysUserEntity;
import com.example.base.security.util.SecurityUtil;
import com.example.base.system.SysAppService;
import com.example.base.system.domain.SysApp;
import com.example.base.utils.ResponseUtils;
import com.example.base.utils.Result;
import com.example.base.utils.SpringContextUtils;
import com.example.mananger.component.ApiHandlerComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Order(-9999)
public class ManangerInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURI();

        SysAppService sysAppService=SpringContextUtils.getBean(SysAppService.class);
        SysApp sysApp=sysAppService.getSysApp(request);
        if(sysApp==null){
            log.info("app 应用拦截器, 未发现app");
            JSONObject jsonObject=Result.errorInfo("app 应用拦截器, 未发现app");
            ResponseUtils.responseJson(response,jsonObject);
            return false;
        }else {
            log.info("app 应用拦截器, appName {} ",sysApp.getAppName());
            log.info("app 应用状态为: {}",sysApp.getAppStatus() ? "app已启动" : "app正在加载中");
            if(!sysApp.getAppStatus()){
                JSONObject jsonObject=Result.errorInfo("app正在加载中");
                ResponseUtils.responseJson(response,jsonObject);
                return false;
            }
        }
        log.info("请求路径为：{}",requestUrl);
        log.info("请求的app为:{}",sysApp.getAppName());
        AppInterceptor appInterceptor= SpringContextUtils.getBean(AppInterceptor.class);
        if(handler instanceof HandlerMethod){
            Boolean isHandler = appInterceptor.valitedApp(request,response,(HandlerMethod) handler);
            if (isHandler != null) {
                if (!isHandler) {
                    return false;
                }
            }
        }

        AppHandlerServer appHandlerServer=SpringContextUtils.getBean(AppHandlerServer.class);
        AppHandler appHandler=appHandlerServer.getAppHandlerByAppName(sysApp.getAppName());
        if(appHandler!=null){
            try {
                //判断app是否需要登录
                if(appHandler.isLogin()){
                    List<String> nologinPath=appHandler.noLoginPath();
                    if(nologinPath!=null && nologinPath.size() > 0){
                        if(nologinPath.contains(requestUrl)){
                            return true;
                        }
                    }
                    AppLoginHandler appLoginHandler=SpringContextUtils.getBean(AppLoginHandler.class);
                    boolean flag=appLoginHandler.login(request,response,sysApp.getAppName());
                    if(!flag){
                        JSONObject result=Result.errorInfo("访问 当前app: "+sysApp.getAppName()+" 未进行登录");
                        ResponseUtils.responseJson(response,result);
                        return false;
                    }
                }
                //app的拦截器
                boolean flag=appHandler.handlerBefore(request,response,sysApp.getAppName());
                if(!flag){
                    return false;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if(handler instanceof ResourceHttpRequestHandler){
            log.info("静态资源 请求地址 {}",request.getRequestURI());
            ResourceHttpRequestHandler requestHandler=(ResourceHttpRequestHandler)handler;
        }
        String path=request.getRequestURI();
        ApiHandlerComponent apiHandlerComponent=SpringContextUtils.getBean(ApiHandlerComponent.class);
        //校验是否具有路径权限
        if(!apiHandlerComponent.handler(path)){
            return false;
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String requestUrl = request.getRequestURI();
        SysAppService sysAppService=SpringContextUtils.getBean(SysAppService.class);
        SysApp sysApp=sysAppService.getSysApp(request);

        AppHandlerServer appHandlerServer=SpringContextUtils.getBean(AppHandlerServer.class);
        AppHandler appHandler=appHandlerServer.getAppHandlerByAppName(sysApp.getAppName());
        if(appHandler!=null) {
            appHandler.handlerBefore(request,response,sysApp.getAppName());
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


}
